﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Omu.Awesome.Mvc.Helpers
{
    public static class AjaxDropdownHelpers
    {
        public static MvcHtmlString AjaxDropdownFor<T, TReturn>(
            this HtmlHelper<T> html,
            Expression<Func<T, TReturn>> prop,
            object value = null,
            string controller = null,
            string parentId = null,
            object htmlAttributes = null,
            string prefix = null,
            IDictionary<string, string> data = null,
            IDictionary<string, object> parameters = null,
            string area = null)
        {
            return AjaxDropdown(html, ExpressionHelper.GetExpressionText(prop), value, controller, parentId, htmlAttributes, prefix, data, parameters, area);
        }

        public static MvcHtmlString AjaxDropdown(this HtmlHelper html, AjaxDropdownParams o)
        {
            o.ReadMeta(html);

            if (o.Controller == null) o.Controller = o.Prop.GetController() + "AjaxDropdown";
            o.Value = o.Value.FromModel(html, o.Prop);

            var hd = o.HtmlAttributes.GetDictionary();
            var h = !html.ViewData.ModelState.IsValidField(o.Prop)
                        ? hd.AddVal("class", "input-validation-error")
                        : hd;
            var info = new AjaxDropdownInfo { HtmlAttributes = h.ToHtml() };
            info.ReadParams(o);
            return html.Partial(Settings.AwesomeFolder + "AjaxDropdown.ascx", info);
        }

        public static MvcHtmlString AjaxDropdown(
            this HtmlHelper html,
            string prop,
            object value = null,
            string controller = null,
            string parentId = null,
            object htmlAttributes = null,
            string prefix = null,
            IDictionary<string, string> data = null,
            IDictionary<string, object> parameters = null,
            string area = null)
        {
            return html.AjaxDropdown(new AjaxDropdownParams
                                  {
                                      Controller = controller,
                                      Data = data,
                                      HtmlAttributes = htmlAttributes,
                                      Parameters = parameters,
                                      ParentId = parentId,
                                      Prefix = prefix,
                                      Prop = prop,
                                      Value = value,
                                      Area = area
                                  });
        }
    }
}